package cn.gx.kevin.Utils;


import cn.gx.kevin.common.user.ILoginUserContext;
import cn.gx.kevin.common.user.LoginUser;
import org.apache.commons.codec.digest.DigestUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;


import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/***
 *@description : 基于redis的用户session，适用于分布式场景
 *@author : kevin.huang
 *@date : 2019/9/26 14:11
 @modified by
 ***/
public class RedisUserContext extends LoginUserContext implements ILoginUserContext {

    @Autowired
    RedissonClient redissonClient;

    @Override
    public void setUpdateRate(int rate) {

    }

    @Override
    public void setExpiry(int expiry) {

    }

    @Override
    public int getExpiry() {
        return 20;
    }

    @Override
    public void updateExpiry(String key) throws Exception {

    }

    @Override
    public String setLoginUser(LoginUser user) throws Exception {
        String key = DigestUtils.md5Hex(user.getId() + "_" + user.getLoginIp());
        user.setUserKey(key);
        RBucket<LoginUser> obj = redissonClient.getBucket(key);
        obj.set(user,this.expiry, TimeUnit.MINUTES);
        return key;
    }

    @Override
    public void logout() throws Exception {
        String key = this.getLoginKeyFromRequest();
        this.logout(key);
    }

    @Override
    public void logout(String key) throws Exception {
        RBucket<LoginUser> obj =  redissonClient.getBucket(key);
        obj.delete();
    }

    @Override
    public void setKeyValue(String key, Object obj) throws Exception {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        bucket.set(obj ,this.expiry , TimeUnit.MINUTES);
    }

    @Override
    public Object getKeyValue(String key) throws Exception {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        Object obj = bucket.get();
        if(obj != null){
            bucket.expireAsync(this.expiry,TimeUnit.MINUTES);
        }
        return obj;
    }

    @Override
    public LoginUser getCurrentUser() throws Exception {
        String key = this.getLoginKeyFromRequest();
        if (key != null) {
            RBucket<LoginUser> bucket =  redissonClient.getBucket(key);
            LoginUser user = bucket.get();
            /*****刷新过期****/
            if(user != null){
                bucket.expireAsync(this.expiry,TimeUnit.MINUTES);
            }
            return user;
        }
        return null;
    }

    @Override
    public void deleteKeyValue(String key) throws Exception {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        bucket.delete();
    }
}
